import { rayMix, raySegs } from '../math/arrayMix.js'
import { plainMatrix, _move } from '../math/index.js'
import {  segCrossPoints, neighbourSegCrossPoints } from './segCross.js'
// 多边形连接线
export const linkPoints = (points) => {
    let lps = []
    for (let i = 0; i < points.length - 1; i++) {
        let p = points[i]
        lps = [...lps, ...rayMix(p, points.slice(i + 1))]
    }
    return lps
}

// 不包含边连线段
export const linkSegments = (points) => {
    let segs = []
    for (let i = 0, len = points.length; i < len - 2; i++) {
        let p = points[i]
        segs.push(...raySegs(p, points.slice(i + 2, i === 0 ? (len - 1) : len)))
    }
    return segs
}



// 多边形连接线交叉点
export const linkCrossPoints = (points) => {
    let segs = linkSegments(points)
    return segCrossPoints(segs)
}
// 线段延长线
const lineExtension = (p1, p2, iterNum = 0) => {
    let p = _move(p2, p1, p2)
    while (iterNum-- > 0) {
        p = _move(p, p1, p)
    }
    return [p2, p]
}

export const edgeExtensionSegs = (points, iterNum) => {
    let len = points.length
    let segs1 = []
    let segs2 = []
    points.forEach((t, i) => {
        let next = points[(i + 1) % len]
        let seg1 = lineExtension(t, next, iterNum)
        let seg2 = lineExtension(next, t, iterNum)
        segs1.push(seg1)
        segs2.push(seg2)
    })
    let n = segs1.length
    let segs = []
    segs1.forEach((t, i) => {
        segs.push(t)
        segs.push(segs2[(i + 2) % n])
    })
    return segs
}
// 延长线
export const edgeExtensionPoints = (points, iterNum) => {
    return plainMatrix(edgeExtensionSegs(points, iterNum))
}



// 延长线交叉点
export const edgeExtensionCrossPoints = (points, iterNum) => {
    let segs = edgeExtensionSegs(points, iterNum)
    return neighbourSegCrossPoints(segs)
}


// 带状
export const stripPoints = (points, n) => {
    let len = points.length
    let matrix = []
    for (let i = 0; i <= len - n; i++) {
        let stack = []
        for (let j = 0; j < n; j++) {
            let p = points[i + j]
            stack.push(p)
        }
        matrix.push(stack)
    }
    return matrix
}

export const stripLoopPoints = (points, n) => {
    let len = points.length
    let matrix = []
    for (let i = 0; i < len; i++) {
        let stack = []
        for (let j = 0; j < n; j++) {
            let p = points[(i + j) % len]
            stack.push(p)
        }
        matrix.push(stack)
    }
    return matrix
}

export const stripFanPoints = (points, n) => {
    let [o, ...rest] = points
    let len = rest.length
    let matrix = []
    for (let i = 0; i <= len - n; i++) {
        let stack = [o]
        for (let j = 0; j < n; j++) {
            let p = rest[(i + j) % len]
            stack.push(p)
        }
        matrix.push(stack)
    }
    return matrix
}